const fs = require('fs');
const path = require('path');
const { minify: minifyHtml } = require('html-minifier');
const CleanCSS = require('clean-css');
const Terser = require('terser');

// 获取指定目录中的所有文件
function getFilesInDirectory(directory) {
    return fs.readdirSync(directory).map(file => path.join(directory, file));
}

// 压缩 HTML 文件
function compressHtml(inputPath, outputPath) {
    const html = fs.readFileSync(inputPath, 'utf8');
    const minifiedHtml = minifyHtml(html, {
        removeComments: true,
        collapseWhitespace: true,
        removeEmptyAttributes: true,
        minifyCSS: false,  // 不压缩内嵌的 CSS
        minifyJS: false    // 不压缩内嵌的 JS
    });
    fs.writeFileSync(outputPath, minifiedHtml);
    console.log(`HTML 文件压缩完成: ${outputPath}`);
}

// 压缩 CSS 文件
function compressCss(inputPath, outputPath) {
    const css = fs.readFileSync(inputPath, 'utf8');
    const minifiedCss = new CleanCSS().minify(css).styles;
    fs.writeFileSync(outputPath, minifiedCss);
    console.log(`CSS 文件压缩完成: ${outputPath}`);
}

// 压缩 JavaScript 文件
async function compressJs(inputPath, outputPath) {
    const js = fs.readFileSync(inputPath, 'utf8');
    const minifiedJs = (await Terser.minify(js)).code;
    fs.writeFileSync(outputPath, minifiedJs);
    console.log(`JS 文件压缩完成: ${outputPath}`);
}

// 主处理函数
async function compressAllFiles() {
    const directory = __dirname;
    const files = getFilesInDirectory(directory);

    for (const file of files) {
        const extname = path.extname(file);
        const basename = path.basename(file, extname);
        const outputDir = path.join(directory, 'compressed');

        if (!fs.existsSync(outputDir)) {
            fs.mkdirSync(outputDir);
        }

        const outputPath = path.join(outputDir, basename + (extname === '.html' ? '.min.html' : extname === '.css' ? '.min.css' : extname === '.js' ? '.min.js' : ''));

        switch (extname) {
            case '.html':
                compressHtml(file, outputPath);
                break;
            case '.css':
                compressCss(file, outputPath);
                break;
            case '.js':
                await compressJs(file, outputPath);
                break;
            default:
                console.log(`文件类型不支持: ${file}`);
                break;
        }
    }
}

// 执行压缩操作
compressAllFiles().catch(error => console.error('压缩过程中发生错误:', error));
